package com.stylefeng.guns.modular.huamao.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.stylefeng.guns.modular.huamao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.huamao.model.Account;
import com.stylefeng.guns.modular.huamao.model.AccountShop;
import com.stylefeng.guns.modular.huamao.model.PayScene;
import com.stylefeng.guns.modular.huamao.model.SktBuyplaque;
import com.stylefeng.guns.modular.huamao.model.SktOrders;
import com.stylefeng.guns.modular.huamao.model.SktOrdersStockscore;
import com.stylefeng.guns.modular.huamao.model.SktSysConfigs;
import com.stylefeng.guns.modular.huamao.model.SktWorkorder;
import com.stylefeng.guns.modular.huamao.model.Users;
import com.stylefeng.guns.modular.huamao.model.UsersRecharge;
import com.stylefeng.guns.modular.huamao.model.UsersUpgrade;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.util.CacheUtil;
import com.stylefeng.guns.modular.huamao.util.MSGUtil;
import com.stylefeng.guns.modular.huamao.util.SessionUtils;

@CrossOrigin
@SuppressWarnings("all")
@Controller
@RequestMapping("/app")
public class AppPayController extends BaseController {

    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IAppSktSysConfigService iAppSktSysConfigService;
    @Autowired
    private IAppSktStylesService iAppSktStylesService;
    @Autowired
    private IAppPaySceneService iAppPaySceneService;
    @Autowired
    private IAppAccountService iAppAccountService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppOrderService iAppOrderService;
    @Autowired
    private IAppUsersUpgradeService iAppUsersUpgradeService;
    @Autowired
    private IAppUsersRechargeService iAppUsersRechargeService;
    @Autowired
    private IAppOrdersStockScoreService iAppOrdersStockScoreService;
    @Autowired
    private IAppSktBuyplaqueSerivce iAppSktBuyplaqueSerivce;
    @Autowired
    private IAppSktWorkOrderService iAppSktWorkOrderService;
    @Autowired
    private IAppAccountShopService iAppAccountShopService;
    @Autowired
    private IAccountService accountService;
   
    /**
     * 收银台（ZJF）
     * @param sceneCode
     * @param orderNo
     * @param isBatch   商城购物时是否从购物车提交订单（0：不是；1：是）
     * @return
     */
    @RequestMapping("/pay/checkstand")
    @ResponseBody
    public AppResult checkstand(@ModelAttribute("sceneCode")String sceneCode,@ModelAttribute("orderNo")String orderNo,@ModelAttribute("isBatch")String isBatch){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if(user==null){
                return AppResult.ERROR("您未登录",-2);
            }
            if (MSGUtil.isBlank(sceneCode)){
                return AppResult.ERROR("请选择业务类型",-1);
            }
            Map<String, Object> orderWhere = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            String sceneCodes = sceneCode.toUpperCase();
            map.put("sceneCode",sceneCodes);
            map.put("userId",user.getUserId());
            PayScene payScene=iAppPaySceneService.selectPayBySceneCode(map);
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> orderInfo = new HashMap<>();
            Map<String, Object> payType = new HashMap<>();
            SktOrders sktOrders=new SktOrders();
            if (MSGUtil.isBlank(payScene)){
                return AppResult.ERROR("没有找到该业务类型",-1);
            }
            payType.put("kaiyuanturnover",payScene.getKaiyuanturnover());
            payType.put("id",payScene.getId());
            payType.put("sceneCode",payScene.getSceneCode());
            payType.put("sceneExplain",payScene.getSceneExplain());
            payType.put("offline",payScene.getOffline());
            payType.put("cash",payScene.getCash());
            payType.put("kaiyuan",payScene.getKaiyuan());
            payType.put("alipay",payScene.getAlipay());
            payType.put("weixin",payScene.getWeixin());
            payType.put("shortcut",payScene.getShortcut());
            payType.put("gateway",payScene.getGateway());
            if (payScene.getKaiyuanturnover()==1){
                Users users = iAppUserService.selectUsersByUserId(user.getUserId());
                if (users.getUserType()==0 || users.getIsStore()==0){
                    payType.put("kaiyuanturnover",0);
                }
            }
            data.put("payType",payType);
            if (MSGUtil.isBlank(orderNo)){
                return AppResult.ERROR("请传入订单号",-1);
            }
            Double payScore =0D;
            Double payKaiyuan=0D;
            Double payShopping=0D;
            switch (sceneCodes){
                //线上订单
                case "BUY_GOODS":
                    Map<String, Object> map1 = new HashMap<>();
                    data.put("orderInfo",false);
                    map1.put("isPay",0);
                    int isBatchs=MSGUtil.isBlank(isBatch)?0:Integer.parseInt(isBatch);
                    if (isBatchs==1){
                        map1.put("orderunique",orderNo);
                    }else {
                        map1.put("orderNo",orderNo);
                    }
                 //   sktOrders=iAppOrderService.selectOrderByIsPay(map1);
                    Double payMoney=iAppOrderService.selectSumTotalMoney(map1);
                    payScore = iAppOrderService.selectSumPayScore(map1);
                    payKaiyuan=iAppOrderService.selectSumPayKaiyuan(map1);
                    payShopping=iAppOrderService.selectSumPayShopping(map1);
                    if (!MSGUtil.isBlank(payMoney)){
                        orderInfo.put("totalMoney",payMoney.toString());
                    }
                    orderInfo.put("orderNo",orderNo);
                    data.put("isBatch",isBatch);
                    break;
                //用户升级
                case "UPGRADE":
                    orderWhere.put("orderNo",orderNo);
                    orderWhere.put("status",0);
                    UsersUpgrade usersUpgrade=iAppUsersUpgradeService.selectUsersUpgradeByOrderNo(orderWhere);
                    orderInfo.put("orderNo",orderNo);
                    orderInfo.put("totalMoney",usersUpgrade.getTotalMoney().toString());
                    orderInfo.put("remark",usersUpgrade.getOrderRemarks());
                    break;
                //用户充值
                case "RECHARGE":
                    orderWhere.put("orderNo",orderNo);
                    orderWhere.put("status",0);
                    UsersRecharge usersRecharge=iAppUsersRechargeService.selectUsersRechargeByOrderNo(orderWhere);
                    orderInfo.put("orderNo",orderNo);
                    orderInfo.put("totalMoney",usersRecharge.getCash().toString());
                    orderInfo.put("remark",usersRecharge.getRemark());
                    break;
                //购买库存积分
                case "BUY_SCORE":
                    orderWhere.put("orderNo",orderNo);
                    orderWhere.put("orderStatus",1);
                    SktOrdersStockscore sktOrdersStockscore=iAppOrdersStockScoreService.selectByOredrNo(orderWhere);
                    orderInfo.put("orderNo",orderNo);
                    orderInfo.put("totalMoney",sktOrdersStockscore.getTotalMoney().toString());
                    orderInfo.put("remark",sktOrdersStockscore.getOrderRemarks());
                    break;
                case "BUY_PLAQUE":
                    orderWhere.put("orderNo",orderNo);
                    orderWhere.put("status",1);
                    SktBuyplaque sktBuyplaque=iAppSktBuyplaqueSerivce.selectByOrderNo(orderWhere);
                    orderInfo.put("orderNo",orderNo);
                    orderInfo.put("totalMoney",sktBuyplaque.getTotalMoney().toString());
                    orderInfo.put("remark",sktBuyplaque.getOrderRemarks());
                    break;
                case "WORK_ORDER":
                    orderWhere.put("orderNo",orderNo);
                    orderWhere.put("status",0);
                    SktWorkorder sktWorkorder=iAppSktWorkOrderService.selectByOrderNo(orderWhere);
                    orderInfo.put("orderNo",orderNo);
                    orderInfo.put("totalMoney",sktWorkorder.getTotalMoney().toString());
                    orderInfo.put("remark",sktWorkorder.getOrderRemarks());
            }
            data.put("orderInfo",orderInfo);
            Account account = iAppAccountService.selectAccountByUserId(user.getUserId());
            AccountShop accountShop = iAppAccountShopService.selectAccountShopByUserId(user.getUserId());
            BigDecimal real=new BigDecimal(orderInfo.get("totalMoney").toString()).multiply(new BigDecimal(100)).setScale(3,BigDecimal.ROUND_HALF_UP);
            SktSysConfigs feeRatio=iAppSktSysConfigService.selectSysConfByFieldCode("kaiyuanFee");
            SktSysConfigs taxRatio = iAppSktSysConfigService.selectSysConfByFieldCode("taxRatio");
            BigDecimal fee=real.multiply(new BigDecimal(feeRatio.getFieldValue()).divide(new BigDecimal(100))).setScale(3,BigDecimal.ROUND_HALF_UP);
            BigDecimal tax=real.multiply(new BigDecimal(taxRatio.getFieldValue()).divide(new BigDecimal(100))).setScale(3,BigDecimal.ROUND_HALF_UP);
            double kaiyuanFee=fee.add(tax).setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue();
            data.put("cash",account.getCash().toString());
            data.put("kaiyuan",account.getKaiyuan().toString());
            data.put("fee",kaiyuanFee);
            data.put("score",account.getScore());
            data.put("payScore",MSGUtil.isBlank(payScore)?0.00:payScore);
            data.put("perKaiyuan",MSGUtil.isBlank(payKaiyuan)?0.00:payKaiyuan);
            data.put("payShopping",MSGUtil.isBlank(payShopping)?0.00:payShopping);

            if (!MSGUtil.isBlank(accountShop)){
                data.put("kaiyuanTurnover",accountShop.getKaiyuanTurnover());
            }else {
                data.put("kaiyuanTurnover",0);
            }
            SktSysConfigs kaiyuanTurnRadio=iAppSktSysConfigService.selectSysConfByFieldCode("kaiyuanturnFee");
            BigDecimal kaiyuanTurnoverFee=real.multiply(new BigDecimal(kaiyuanTurnRadio.getFieldValue()).divide(new BigDecimal(100))).setScale(3,BigDecimal.ROUND_HALF_UP);
            data.put("kaiyuanTurnoverFee",kaiyuanTurnoverFee.doubleValue());
            return AppResult.OK("操作成功",data);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("失败");
        }
    }
    @RequestMapping("/compareShopping")
    public AppResult compareShopping(BigDecimal shopping,String userId){
        Map<String, Object> map = accountService.compareShopping(shopping, userId);
        if ("00".equals(map.get("code").toString())){
          return   AppResult.ERROR(map.get("msg").toString());
        }
       return AppResult.OK(map.get("code"));
    }
}
